package icu.gking.cart_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import icu.gking.cart_system.common.Result;
import icu.gking.cart_system.dto.CartAddDTO;
import icu.gking.cart_system.pojo.Cart;
import icu.gking.cart_system.pojo.Commodity;
import icu.gking.cart_system.pojo.User;
import icu.gking.cart_system.service.CartService;
import icu.gking.cart_system.service.CommodityService;
import icu.gking.cart_system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CommodityService commodityService;

    @Autowired
    private UserService userService;

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public Result<Cart> addToCart(@RequestBody CartAddDTO cartAddDTO) {
        try {
            // 参数校验
            if (cartAddDTO.getUserId() == null || cartAddDTO.getCommodityId() == null || cartAddDTO.getAmount() == null) {
                return Result.error("参数不完整");
            }
            if (cartAddDTO.getAmount() <= 0) {
                return Result.error("商品数量必须大于0");
            }

            // 检查商品是否存在且有库存
            Commodity commodity = commodityService.getById(cartAddDTO.getCommodityId());
            if (commodity == null) {
                return Result.error("商品不存在");
            }
            if (commodity.getStatus() != 1) {
                return Result.error("商品已下架");
            }
            if (commodity.getStock() < cartAddDTO.getAmount()) {
                return Result.error("库存不足");
            }

            // 检查购物车是否已有该商品
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", cartAddDTO.getUserId())
                    .eq("commodity_id", cartAddDTO.getCommodityId());
            Cart existingCart = cartService.getOne(queryWrapper);

            if (existingCart != null) {
                // 更新现有购物车项
                int newAmount = existingCart.getAmount() + cartAddDTO.getAmount();
                if (newAmount > commodity.getStock()) {
                    return Result.error("库存不足");
                }
                existingCart.setAmount(newAmount);
                existingCart.setMoney(existingCart.getPrice() * newAmount);
                cartService.updateById(existingCart);
                return Result.success(existingCart);
            } else {
                // 创建新的购物车项
                Cart cart = new Cart();
                cart.setUserId(cartAddDTO.getUserId());
                cart.setCommodityId(cartAddDTO.getCommodityId());
                cart.setCommodityName(commodity.getCommodityName());
                cart.setPrice(commodity.getPrice());
                cart.setAmount(cartAddDTO.getAmount());
                cart.setMoney(commodity.getPrice() * cartAddDTO.getAmount());
                cartService.save(cart);
                return Result.success(cart);
            }
        } catch (Exception e) {
            log.error("添加购物车失败", e);
            return Result.error("添加购物车失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的购物车列表
     */
    @GetMapping("/list/{userId}")
    public Result<List<Cart>> getCartList(@PathVariable Integer userId) {
        try {
            log.info("获取用户购物车列表 - userId: {}", userId);
            if (userId == null) {
                return Result.error("用户未登录");
            }

            // 验证用户是否存在
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 获取购物车列表
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            List<Cart> cartList = cartService.list(queryWrapper);

            // 检查商品状态和库存
            List<Cart> validCartItems = new ArrayList<>();
            List<Cart> invalidCartItems = new ArrayList<>();

            for (Cart cart : cartList) {
                Commodity commodity = commodityService.getById(cart.getCommodityId());
                if (commodity == null || commodity.getStatus() == 0) {
                    // 商品不存在或已下架
                    cart.setValid(false);
                    cart.setInvalidReason("商品已下架");
                    invalidCartItems.add(cart);
                } else if (commodity.getStock() < cart.getAmount()) {
                    // 库存不足
                    cart.setValid(false);
                    cart.setInvalidReason("库存不足");
                    // 自动调整数量到最大库存
                    cart.setAmount(commodity.getStock());
                    cart.setMoney(cart.getPrice() * commodity.getStock());
                    cartService.updateById(cart);
                    invalidCartItems.add(cart);
                } else {
                    cart.setValid(true);
                    validCartItems.add(cart);
                }
            }

            // 获取所有商品的卖家信息
            Set<Integer> sellerIds = cartList.stream()
                    .map(cart -> {
                        Commodity commodity = commodityService.getById(cart.getCommodityId());
                        return commodity != null ? commodity.getSellerId() : null;
                    })
                    .filter(sellerId -> sellerId != null)
                    .collect(Collectors.toSet());

            // 批量查询卖家信息
            final Map<Integer, String> sellerMap = new HashMap<>();
            if (!sellerIds.isEmpty()) {
                List<User> sellers = userService.listByIds(sellerIds);
                sellerMap.putAll(sellers.stream()
                        .collect(Collectors.toMap(User::getUserId, User::getUserName)));
            }

            // 设置卖家名称
            cartList.forEach(cart -> {
                Commodity commodity = commodityService.getById(cart.getCommodityId());
                if (commodity != null) {
                    cart.setSellerName(sellerMap.getOrDefault(commodity.getSellerId(), "未知商家"));
                }
            });

            // 合并有效和无效商品列表
            cartList = new ArrayList<>();
            cartList.addAll(validCartItems);
            cartList.addAll(invalidCartItems);

            log.info("用户购物车列表 - userId: {}, 商品数量: {}", userId, cartList.size());
            return Result.success(cartList);
        } catch (Exception e) {
            log.error("获取购物车列表失败 - userId: {}", userId, e);
            return Result.error("获取购物车列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的有效购物车商品列表
     */
    @GetMapping("/valid/{userId}")
    public Result<List<Cart>> getValidCartList(@PathVariable Integer userId) {
        try {
            log.info("获取用户有效购物车列表 - userId: {}", userId);
            if (userId == null) {
                return Result.error("用户未登录");
            }

            // 验证用户是否存在
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 获取购物车列表
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            List<Cart> cartList = cartService.list(queryWrapper);

            // 筛选有效商品
            List<Cart> validCartItems = new ArrayList<>();

            for (Cart cart : cartList) {
                Commodity commodity = commodityService.getById(cart.getCommodityId());
                if (commodity != null && commodity.getStatus() == 1 && commodity.getStock() >= cart.getAmount()) {
                    cart.setValid(true);
                    validCartItems.add(cart);
                }
            }

            return Result.success(validCartItems);
        } catch (Exception e) {
            log.error("获取有效购物车列表失败 - userId: {}", userId, e);
            return Result.error("获取有效购物车列表失败：" + e.getMessage());
        }
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/update")
    public Result<Cart> updateCart(@RequestBody CartAddDTO cartAddDTO) {
        try {
            Cart cart = cartService.getById(cartAddDTO.getCartId());
            if (cart == null) {
                return Result.error("购物车项不存在");
            }

            // 检查库存
            Commodity commodity = commodityService.getById(cart.getCommodityId());
            if (commodity == null) {
                return Result.error("商品不存在");
            }
            if (cartAddDTO.getAmount() > commodity.getStock()) {
                return Result.error("库存不足");
            }

            cart.setAmount(cartAddDTO.getAmount());
            cart.setMoney(cart.getPrice() * cartAddDTO.getAmount());
            cartService.updateById(cart);
            return Result.success(cart);
        } catch (Exception e) {
            return Result.error("更新购物车失败：" + e.getMessage());
        }
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/delete/{cartId}")
    public Result<Boolean> deleteCart(@PathVariable Integer cartId) {
        try {
            return Result.success(cartService.removeById(cartId));
        } catch (Exception e) {
            return Result.error("删除购���车失败：" + e.getMessage());
        }
    }
} 